layui.use(['element','table','layer','form'], function(){
  var table = layui.table;
  var layer = layui.layer;
  var form=layui.form
  , $ = layui.jquery;
	util = layui.util;

  table.render({
	    elem: '#basicBlockTable',
	    height: 'full-150',
	    url:  "/basicBlock/blockTable", //数据接口
	    method: 'post',
	    request:{
			page: 'pageNum', //页码的参数名称，默认：page
			limit: 'pageSize' //每页数据量的参数名，默认：limit
	    },
	    where: {
			blockName: "",
			community:$(window.parent.document).find("#community").val()
		},
	    page: true, //开启分页
	    cols: [[ //表头
	    	{type:'numbers'}
			,{field: 'blockId', title: '楼栋ID',width:180,align:'center' }
	    	,{field: 'blockName', title: '楼栋名称',width:120,align:'center'}
	    	,{field: 'blockNo', title: '楼栋编号',width:120,align:'center'}
			,{field:'blockType',align : 'center', title:'类型',templet:function(d){
					return parseType(d.blockType);
				}}
	    	,{field: 'blockDesc', title: '楼栋描述',width:120,align:'center' }
	    	,{field: 'blockAddress', title: '大楼地址',width:130, align:'center' }
	    	,{field: 'blockFloor', title: '楼层数量',width:120, align:'center'  }
	        ,{field: 'createTime', title: '添加时间',width:170, align:'center',templet: function (d) {
					return util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss");
				}    }
	        , {field: 'right', title: '操作', align:'center',width:200, fixed: 'right',templet:function(data){
	    	  var op = '<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>';
	    	  op+='<a class="layui-btn layui-btn-xs" lay-event="delete">删除</a>';
	    	  return op;
	      }
	      }
	    ]]

	  });

    //添加楼栋信息
	addBlock = function () {
		$("#block_up").hide();
		$("#block_form").show();
		$("#block_form").attr("disabled", false);
		$("#block_form").attr("class", "layui-btn");
		$("#product_form")[0].reset();
		layer.open({
			type: 1
			, title: '新增'
			, shadeClose: true
			, area: ['500px', '80%']
			, content: $('#blockAdd')
		});
	};

	//操作列
    table.on('tool(basicBlockTable)', function(obj){
	    var data = obj.data;
		if(obj.event === 'delete'){
			var companyId = $(window.parent.document).find("#community").val();
			var code = $(window.parent.document).find("#community option:selected").attr("id");
			layer.confirm('是否确认删除'+data.blockName+'的信息？', {
				btn: ['确认', '返回'] //按钮
			}, function () {
				var index = layer.load(2, {
					shade: [0.4, '#000'],
					content: '提交中...',
					success: function (layero) {
						layero.find('.layui-layer-content').css({
							'padding-top': '40px',
							'width': '200px'
						});
					}
				});
				$.post('/basicBlock/delBlock',{bid:data.blockId, companyId:companyId,code:code},function (res) {
					if(res.resultCode === '000'){
						layer.msg('删除成功',{
							time:500,
							end:function () {
								reloadBlockList();
							}
						})
					}else{
						layer.msg(res.resultDesc);
					}
					layer.close(index);
				})
			})
		}else if (obj.event === 'edit'){
			$("#block_up").show();
			$("#block_form").hide();
			$("#block_up").attr("disabled", false);
			$("#block_up").attr("class", "layui-btn");
			// var blockName = data.blockName;
			// if(data.blockName.indexOf("栋")>-1 ){
			// 	blockName = data.blockName.substr(0,data.blockName.length-1);
			// }
			$("#blockId").val(data.blockId);
			form.val('product_form',{
				// 'blockId': data.blockId,
				'blockName': data.blockName,
				'blockNo': data.blockNo,
				'blockType': data.blockType,
				'blockDesc':data.blockDesc,
				'blockAddress':data.blockAddress,
				'blockFloor': data.blockFloor,
			});
			form.render();
			layer.open({
				type: 1
				, title: '编辑信息'
				, shadeClose: true
				, area: ['500px', '80%']
				, content: $('#blockAdd')
			});
		}
	});

	//提交楼栋信息表单
	form.on('submit(block_form)',function(data){
		$("#block_form").attr("disabled", true);
		$("#block_form").attr("class", "layui-btn layui-btn-disabled");
		var inFun = 0;
		layer.confirm('是否确认提交楼栋信息？', {
			btn: ['确认', '返回'] //按钮
		}, function () {
			if(inFun === 1){
				return;
			}
			inFun = 1;
			var index = layer.load(2, {
				shade: [0.4, '#000'],
				content: '提交中...',
				success: function (layero) {
					layero.find('.layui-layer-content').css({
						'padding-top': '40px',
						'width': '200px'
					});
				}
			});
			// data.field.blockName = data.field.blockName+'栋';
			data.field.companyId = $(window.parent.document).find("#community").val();
			data.field.housingEstateId = $(window.parent.document).find("#community option:selected").attr("id");
			$.post("/basicBlock/addBlock", data.field, function (data) {
				layer.closeAll();
				if(data.resultCode === "000"){
					layer.msg('提交成功',{
						time:500,
						end:function () {
							reloadBlockList();
						}
					})
				}else{
					layer.close(index);
					layer.msg( data.resultDesc );
					$("#block_form").attr("disabled", false);
					$("#block_form").attr("class", "layui-btn");
				}
			})
		}, function () {
			layer.closeAll();
			return false;
		});
		return false;//返回false 防止二次提交
	});

	//更新楼栋信息
	form.on('submit(block_up)',function(data){
		$("#block_up").attr("disabled", true);
		$("#block_up").attr("class", "layui-btn layui-btn-disabled");
		var inFun = 0;
		layer.confirm('是否确认更新楼栋信息？', {
			btn: ['确认', '返回'] //按钮
		}, function () {
			if(inFun === 1){
				return;
			}
			inFun = 1;
			var index = layer.load(2, {
				shade: [0.4, '#000'],
				content: '提交中...',
				success: function (layero) {
					layero.find('.layui-layer-content').css({
						'padding-top': '40px',
						'width': '200px'
					});
				}
			});
			// data.field.blockName = data.field.blockName+'栋';
			data.field.companyId = $(window.parent.document).find("#community").val();
			data.field.housingEstateId = $(window.parent.document).find("#community option:selected").attr("id");
			$.post("/basicBlock/upBlock", data.field, function (data) {
				if(data.resultCode === "000"){
					layer.closeAll();
					layer.msg('更新成功',{
						time:500,
						end:function () {
							reloadBlockList();
						}
					})
				}else{
					layer.close(index);
					layer.msg( data.resultDesc );
					$("#block_up").attr("disabled", false);
					$("#block_up").attr("class", "layui-btn");
				}
			})
		}, function () {
			layer.closeAll();
			return false;
			$("#block_up").attr("disabled", false);
			$("#block_up").attr("class", "layui-btn");
		});
		return false;//返回false 防止二次提交
	});

	function reloadBlockList(){
		table.reload('basicBlockTable', {
			page: {
				curr: 1 //重新从第 1 页开始
			}
			,where: {
				blockName: $('#searchBlockName').val(),
				community: $(window.parent.document).find("#community").val()
			}
		});
	}

	//查询楼栋
	form.on('submit(search_block)',function () {
		//执行重载
		reloadBlockList();
		return false;
	});

	// 同步数据
	$("#sync").on('click', function (){
		layer.confirm('同步数据耗时较长，是否继续？', {
			btn: ['确认', '取消'] //按钮
		}, function () {
			var index = layer.load(2, {
				shade: [0.4, '#000'],
				content: '同步中...',
				success: function (layero) {
					layero.find('.layui-layer-content').css({
						'padding-top': '40px',
						'width': '200px'
					});
				}
			});
			var companyId = $(window.parent.document).find("#community").val();
			$.post('/basicBlock/syncData',{companyId:companyId},function (res) {
				if(res.resultCode === '000'){
					layer.msg('同步成功',{
						time:500,
						end:function () {
							reloadBlockList();
						}
					})
				}else{
					layer.msg(res.resultDesc);
				}
				layer.close(index);
			});
		})
	});

	// 导入
	$("#import").on('click', function (){
		layer.open({
			type: 1
			,title: '上传文件'
			,area: ['45%','30%']
			,content: $('#upload')
		});
	});

	// 导出
	$("#exportAll").on('click', function (){
		var communityId = $(window.parent.document).find("#community").val();
		if(communityId === ""){
			return layer.msg("小区id为空!",{icon:5});
		}
		downloadFile("/basicBlock/exportBlock2Excel?communityId="+communityId);
	});

	// 下载模板
	$("#down_block_template").on('click', function (){
		$('#downButton')[0].click();
	});
	//提交导入信息
	form.on('submit(upload_form)',function(){
		$("#upload_form").attr("disabled", true);
		$("#upload_form").attr("class", "layui-btn layui-btn-disabled");
		var formData = new FormData();
		formData.append("file",$("#uploadExcel")[0].files[0]);
		formData.append("community",$(window.parent.document).find("#community").val());
		formData.append("housingEstateId",$(window.parent.document).find("#community option:selected").attr("id"));
		layer.load();
		$.ajax({
			url:'/basicBlock/uploadBlock',
			type: 'POST',
			data: formData,
			processData: false,
			contentType:false,
			success:function(res){
				if (res.resultCode === "000") {
					reloadBlock();
					layer.msg('导入成功!',{icon: 1});
				}else {
					layer.msg(res.resultDesc,{
						time:5000,
					})
				}
				setTimeout(function () {
					layer.closeAll();
				},1000);
				$("#uploadExcel").val("");
				$("#file_name").val("");
				$("#upload_form").attr("disabled", false);
				$("#upload_form").attr("class", "layui-btn");
			}

		});
		return false;
	});

	$("#uploadProductBtn").on("click",function(){
		$("#uploadExcel").click();
	});
	$("#uploadExcel").on("change",function(){
		var name = $("#uploadExcel").val();
		var fileType = name.substring(name.lastIndexOf(".")+1);
		if(fileType !== "xls" && fileType !== "xlsx"){
			layer.msg("亲，请选择正确的excel格式哦!",{icon:5});
			$("#upload_form").attr("disabled", true);
			$("#upload_form").addClass("layui-btn-disabled");
		}else {
			$("#upload_form").attr("disabled", false);
			$("#upload_form").removeClass("layui-btn-disabled");
			var index = name.lastIndexOf("\\")+1;
			$("#file_name").val(name.substring(index));
		}
	});
})

function reloadBlock(){
	location.reload();
}
function parseType(type) {
	switch (type) {
		case 1: return "出入口";
		case 2: return "楼栋";
		default: return "-";
	}
}